﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ModeloGaleriaNET;
using CADs;
using System.ComponentModel;
using SeguridadGaleria;

namespace GaleriaNET
{
    /// <summary>
    /// Lógica de interacción para MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Brush brushNormal;
        private UserConnData conn;
        private DBConnData dbconn;
        private string originalName;
        private string originalPass;
        private BackgroundWorker worker;
        private Usuario user;
        private string login, password;
        private UsuarioCAD uCAD;
        private IAuditoria auditoria;

        public MainWindow()
        {
            InitializeComponent();
            lbError.FontStyle = FontStyles.Italic;
            brushNormal = tbUserName.BorderBrush;
            conn = UserConnData.Instance;
            dbconn = DBConnData.Instance;
            auditoria = new AuditoriaBD();

            worker = new BackgroundWorker();
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            user = uCAD.GetUsuarioByLoginPassword(login, Utilities.EncriptarSHA1(password));
        }

        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            _busyIndicator.IsBusy = false;
            if (user == null)
            {
                auditoria.Mensaje(new object[]{}, 
                    TiposAuditoria.Ordinal(TiposAuditoria.TIPO_AUDITORIA.ACCESO_DENEGADO), -1);
                lbError.Content = "Datos incorrectos";
                lbError.Visibility = Visibility.Visible;
                tbUserName.BorderBrush = new SolidColorBrush(Colors.Red);
                pbPassword.BorderBrush = new SolidColorBrush(Colors.Red);
                return;
            }
            else // Datos correctos
            {
                auditoria.Mensaje(new object[] { },
                    TiposAuditoria.Ordinal(TiposAuditoria.TIPO_AUDITORIA.ACCESO_CORRECTO), user.Id);

                if (!originalPass.Equals(password) || !originalName.Equals(login))
                {
                    if (cbRecordarDatos.IsChecked == true)
                    {
                        conn.User = login;
                        conn.Password = password;
                        conn.Save();
                    }
                }
                new UserWindow(user, uCAD).Show();
                Close();
            }
        }

        private void btCancelar_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void btAceptar_Click(object sender, RoutedEventArgs e)
        {
            login = tbUserName.Text;
            password = pbPassword.Password;

            // Faltan datos de acceso
            if (string.IsNullOrWhiteSpace(login) || string.IsNullOrWhiteSpace(password))
            {
                lbError.Content = "Rellena todos los campos";
                lbError.Visibility = Visibility.Visible;

                if (string.IsNullOrWhiteSpace(login))
                    tbUserName.BorderBrush = new SolidColorBrush(Colors.Red);
                if (string.IsNullOrWhiteSpace(password))
                    pbPassword.BorderBrush = new SolidColorBrush(Colors.Red);

                return;
            }

            if (!worker.IsBusy)
            {
                _busyIndicator.IsBusy = true;
                worker.RunWorkerAsync();
            }
        }

        private void tbUserName_GotFocus(object sender, RoutedEventArgs e)
        {

            lbError.Visibility = Visibility.Hidden;
            tbUserName.BorderBrush = brushNormal;
            pbPassword.BorderBrush = brushNormal;
        }

        private void pbPassword_GotFocus(object sender, RoutedEventArgs e)
        {
            lbError.Visibility = Visibility.Hidden;
            tbUserName.BorderBrush = brushNormal;
            pbPassword.BorderBrush = brushNormal;
        }

        private void LoginWindow_Loaded(object sender, RoutedEventArgs e)
        {
            ConfigWindow config;
            ConfigServerWindow configServer;

            if (dbconn.IsEmpty())
            {
                Hide();
                config = new ConfigWindow(-1);
                config.ShowDialog();

                if (config.Success == true) // Hay base de datos correcta con la que conectarse
                {
                    if (ServerConnData.Instance.IsEmpty()) // Forzamos también a que haya datos en el servidor
                    {
                        configServer = new ConfigServerWindow("moraDmp30", 1);
                        configServer.ShowDialog();
                        if (configServer.Success == true)
                        {
                            uCAD = new UsuarioCAD();
                            Show();
                            InitFields();
                        }
                        else
                        {
                            // Abre la aplicación, usuario nulo
                            new UserWindow(null, null).Show();
                            Close();
                        }
                    }
                    else
                    {
                        uCAD = new UsuarioCAD();
                        Show();
                        InitFields();
                    }
                }
                else if (config.Success == false)
                {
                    // Abre la aplicación, usuario nulo
                    new UserWindow(null, null).Show();
                    Close();
                }
            }
            else
            {
                // Si es correcta, formulario de Login, si no, abre la aplicación, usuario nulo
                if (dbconn.TestConnection())
                {
                    if (ServerConnData.Instance.IsEmpty())
                    {
                        Hide();
                        configServer = new ConfigServerWindow("moraDmp30", 1);
                        configServer.ShowDialog();

                        if (configServer.Success == true)
                        {
                            uCAD = new UsuarioCAD();
                            Show();
                            InitFields();
                        }
                        else
                        {
                            // Abre la aplicación, usuario nulo
                            new UserWindow(null, null).Show();
                            Close();
                        }
                    }
                    else
                    {
                        uCAD = new UsuarioCAD();
                        InitFields();
                    }
                }
                else
                {
                    Close();
                    new UserWindow(null, null).Show();
                }
            }
        }

        private void InitFields()
        {
            if (!conn.IsEmpty())
            {
                originalName = tbUserName.Text = conn.User;
                originalPass = pbPassword.Password = conn.Password;
            }
            else
            {
                originalName = string.Empty;
                originalPass = string.Empty;
            }
        }
    }
}
